package de.tudresden.inf.ggp.basicplayer;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;

public class GDLStatesConfig {

	private int GDLCount;
	private String GDLs;
	private File file=new File("source//de//tudresden//inf//ggp//basicplayer//GDLConfig.atx");
	private int index;//the index of the String(GDL) in GDLs, which we searched
	
	public GDLStatesConfig(){
		try {
			this.GDLCount=0;
			this.GDLs="";
			file.createNewFile();
			loadFromFile();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	public boolean loadFromFile(){

		try {
			ObjectInputStream objInputStream=new ObjectInputStream(new FileInputStream(file));
			GDLCount=(Integer)objInputStream.readObject();
			GDLs=(String)objInputStream.readObject();
			objInputStream.close();
		} catch (FileNotFoundException e) {
			e.printStackTrace();
			return false;
		} catch (IOException e) {
			e.printStackTrace();
			return false;
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
			return false;
		}
		return true;
	}	
	
	public boolean saveToFile(){
		try {
			ObjectOutputStream objOutputStream=new ObjectOutputStream(new FileOutputStream(file));
			objOutputStream.writeObject(GDLCount);
			objOutputStream.writeObject(GDLs);
			objOutputStream.close();
		} catch (FileNotFoundException e) {
			e.printStackTrace();
			return false;
		} catch (IOException e) {
			e.printStackTrace();
			return false;
		}
		return true;
	}
	
	public boolean searchGDL(String TheGDL){
		index=GDLs.indexOf(TheGDL);
		if(index!=-1){
			return true;
		}
		return false;
	}
	
	public CListStates getListStates(String TheGDL){
		if(this.searchGDL(TheGDL)){
			String name="";
			int tmp=index+TheGDL.length();
			while(GDLs.charAt(tmp)!='.'){
				name+=GDLs.charAt(tmp);
				tmp++;
			}
			name+=".atx";
			CListStates cls=new CListStates();
			try {
				cls.loadFromFile(name);
			} catch (Exception e) {
				e.printStackTrace();
			}
			index=0;
			return cls;
		}
		
		return null;
	}
	
	public void addGDLandStates(String TheGDL, CListStates ListStates){
		if(this.searchGDL(TheGDL)){
			String name="";
			int tmp=index+TheGDL.length();
			while(GDLs.charAt(tmp)!='.'){
				name+=GDLs.charAt(tmp);
				tmp++;
			}
			name+=".atx";
			ListStates.saveToFile(name);
			index=0;
		}else{
			this.GDLCount++;
			this.GDLs+=TheGDL+String.valueOf(GDLCount)+".atx";
			this.saveToFile();
			ListStates.saveToFile(String.valueOf(GDLCount)+".atx");
			
		}
	}
	
}
